﻿using Mapster;
using PCL.Application.BaseUsers.Services;
using PLC.Application.BaseUserPermissions.Services;
using PLC.Interface.BaseUserPermissions;
using PLC.Interface.BaseUsers;
using System.Collections.Generic;
using System.Threading.Tasks;
using YWM;
using YWM.Dto;

namespace PCL.Application.BaseUsers
{
    public class BaseUserAppService : IBaseUserAppService
    {
        private readonly IBaseUserService _baseUserService = YApp.Resolve<IBaseUserService>();

        private readonly IBaseUserPermissionService _baseUserPermissionService = YApp.Resolve<IBaseUserPermissionService>();

        public Task<PagedResultDto<BaseUserResultDto>> GetAll(BaseUserResultRequestDto input)
        {
            return _baseUserService.GetAll(input);
        }

        public async Task<IReadOnlyList<BaseUserPermissionDto>> GetPermissions(string account)
        {
            PagedResultDto<BaseUserPermissionDto> pagedResultDto = await _baseUserPermissionService.GetAll(new BaseUserPermissionResultRequestDto { Account = account });
            return pagedResultDto.Items;
        }

        public async Task<BaseUserResultDto> Save(BaseUserDto input, List<BaseUserPermissionDto> permissions)
        {
            BaseUserResultDto userResultDto;
            if (input.Id > 0)
            {
                userResultDto = await _baseUserService.Update(input);
            }
            else
            {
                BaseUserCreateDto userCreateDto = input.Adapt<BaseUserCreateDto>();
                userResultDto = await _baseUserService.Create(userCreateDto);
            }
            await _baseUserPermissionService.Delete(input.Account);
            foreach (BaseUserPermissionDto item in permissions)
            {
                await _baseUserPermissionService.Create(item);
            }
            return userResultDto;
        }

        public async Task Delete(BaseUserDto input)
        {
            await _baseUserPermissionService.Delete(input.Account);
            await _baseUserService.Delete(input);
        }

        public Task ChangePassword(UserPasswordDto input)
        {
            return _baseUserService.ChangePassword(input);
        }
    }
}
